import { useMemo, memo, useEffect, useState, useCallback } from 'react';
import { Breadcrumb } from 'antd';
import { useLocation, Link } from 'react-router-dom';
import { HomeOutlined, MoreOutlined } from '@ant-design/icons';

import { useSelector } from 'react-redux';

const BreadcrumbList = memo(() => {
    const location = useLocation();
    const menus = useSelector((state) => state.global.menus);
    const [screenWidth, setScreenWidth] = useState(window.innerWidth);
    
    // 响应式断点配置
    const BREAKPOINTS = {
        MOBILE: 500,    // 移动端
        TABLET: 800,   // 平板
        DESKTOP: 1000   // 桌面端
    };
    
    // 根据屏幕宽度确定最大显示的面包屑项目数
    const getMaxVisibleItems = useCallback((width) => {
        if (width < BREAKPOINTS.MOBILE) return 1;      // 移动端只显示首页
        if (width < BREAKPOINTS.TABLET) return 2;      // 平板显示首页+当前页
        if (width < BREAKPOINTS.DESKTOP) return 3;     // 小桌面显示首页+中间+当前页
        return 5; // 大桌面显示全部
    }, [BREAKPOINTS]);
    
    // 监听窗口大小变化
    useEffect(() => {
        let resizeTimer;
        
        const handleResize = () => {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(() => {
                setScreenWidth(window.innerWidth);
            }, 500);
        };
        
        window.addEventListener('resize', handleResize, { passive: true });
        
        return () => {
            clearTimeout(resizeTimer);
            window.removeEventListener('resize', handleResize, { passive: true });
        };
    }, []);
    
     // 递归查找菜单项
    const findMenuByPath = (path, menuList) => {
        for (const menu of menuList) {
            if (menu.key === path) {
                return menu;
            }
            if (menu.children) {
                const found = findMenuByPath(path, menu.children);
                if (found) {return found;}
            }
        }
        return null;
    };

    // 生成完整的面包屑项目
    const fullBreadcrumbItems = useMemo(() => {
        const pathSnippets = location.pathname.split('/').filter(i => i);
        
        const items = [];
        
        // 如果是首页，直接返回首页
        if (pathSnippets.length === 0) {
            items.push({
                title: <HomeOutlined />,
                key: 'home'
            });
            return items;
        }
        
        // 添加首页（可点击）
        items.push({
            title: <Link to="/"><HomeOutlined /></Link>,
            key: 'home'
        });

        let url = '';
        // 根据当前路径生成面包屑
        pathSnippets.forEach((snippet, index) => {
            url += `/${snippet}`;
            const menu = findMenuByPath(url, menus);
            
            if (!menu) {
                return;
            }
            
            // 判断是否为最后一项（当前页面）
            const isLastItem = index === pathSnippets.length - 1;
            
            items.push({
                title: isLastItem ? 
                    menu.label : 
                    <Link to={url}>{menu.label}</Link>,
                key: url
            });
        });
        
        return items;
    }, [location.pathname, menus]);

    // 根据屏幕宽度智能截取面包屑项目
    const breadcrumbItems = useMemo(() => {
        const maxItems = getMaxVisibleItems(screenWidth);
        const items = [...fullBreadcrumbItems];
        
        // 如果项目数量在限制内，直接返回
        if (items.length <= maxItems) {
            return items;
        }
        
        // 智能截取策略
        if (maxItems === 1) {
            // 移动端：只显示首页
            return [items[0]];
        }
        
        if (maxItems === 2) {
            // 平板：显示首页和当前页
            return [items[0], items[items.length - 1]];
        }
        
        // 桌面端：显示首页、省略号、最后几项
        const result = [items[0]]; // 首页
        
        // 添加省略号
        result.push({
            title: <MoreOutlined />,
            key: 'more'
        });
        
        // 添加最后几项（除去首页和省略号的位置）
        const remainingCount = maxItems - 2;
        const remainingItems = items.slice(-remainingCount);
        result.push(...remainingItems);
        
        return result;
    }, [fullBreadcrumbItems, screenWidth, getMaxVisibleItems]);

    return (
        <Breadcrumb items={breadcrumbItems} />
    );
});
export default BreadcrumbList;